package com.djsblog.background.controller;

import java.util.Date;
import java.util.List;

import com.djsblog.entity.Message;
import com.djsblog.entity.PageBean;
import com.djsblog.entity.User;
import com.djsblog.enums.Options;
import com.djsblog.interceptor.AdminInterceptor;
import com.djsblog.service.MessageService;
import com.djsblog.service.impl.MessageServiceImpl;
import com.djsblog.util.CodeUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
/**
 * 信息控制
 * @author 但劲松
 *
 */
@Before(AdminInterceptor.class)
public class MessageController extends Controller{

	private MessageService messageService = new MessageServiceImpl();
	/**
	 * 导航--缺省方法
	 */
	public void index(){
		setAttr("mainPage", "/back/message/messageTable.jsp");
		setAttr("message", true);
		setAttr("pathNow", "收信箱");
		render("/back/main.jsp");
	}
	/**
	 * 列表方法
	 */
	public void ajaxList(){
		PageBean pageBean = PageBean.creat(getPara("page"), Options.PAGESIZE+"");
		Message s_message = getModel(Message.class,"s_message");
		s_message.setCreated(new Date());
		List<Message> messageList = messageService.find(s_message , pageBean); 
		long total = messageService.count(s_message);
		//判断收信还是发信
		String sendOrGet = s_message.getSendId()!=null?"send":"get";
		String[] str = CodeUtil.messageCode(messageList, pageBean, new String[]{total+"",sendOrGet});
		setAttr("total", total);
		setAttr("thead", str[0]);
		setAttr("tbody", str[1]);
		setAttr("tfoot", str[2]);
		//重载session中的数据条数
		if(getSessionAttr("currentUser")!=null){
			User currentUser = getSessionAttr("currentUser");
			if(currentUser!=null){
				Long mesCount = Db.queryLong("SELECT COUNT(*) FROM message WHERE getId="+currentUser.getId()+" AND get_del=FALSE AND state='unRead'");
				setSessionAttr("mesCount", mesCount);
			}
		}
		renderJson();
	}
	/**
	 * id取实体
	 */
	public void ajaxGetById(){
		Message message = messageService.getById(getParaToLong("id"),getPara("read"));
		setAttr("message", message);
		renderJson();
	}
	/**
	 * 保存方法
	 */
	public void ajaxSave(){
		Message message = getModel(Message.class,"message");
		if(StrKit.notBlank(getPara("nickName")))
			message.setGetId(Db.queryLong("select id from user where nickName='"+getPara("nickName")+"' limit 0,1"));
		if(messageService.save(message))
			setAttr("success", true);
		else
			setAttr("success", false);
		renderJson();
	}
	/**
	 * 批量恢复或者删除
	 */
	public void ajaxDeleteOrComeback(){
		String del = getPara("del");
		String[] ids=getPara("ids").split(",");
		boolean flag = false;
		for(String id:ids)
			flag=messageService.deleteOrComeback(Long.parseLong(id), del);
		if(flag)
			setAttr("success", true);
		else
			setAttr("success", false);
		renderJson();
	}
}
